package com.ctyon.watchmanager.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ctyon.common.util.DataUtil;
import com.ctyon.watchmanager.R;

import androidx.annotation.NonNull;

/**
 * CreateDate：19-7-22 on 上午10:01
 * Describe:
 * Coder: lee
 */
public class EditDialog extends Dialog {

    private EditDialogCallback editDialogCallback;
    private EditText editText;
    private TextView titleText;
    private Context context;
    private String title;
    private String hint;
    private String text;

    public EditDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        this.context = context;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setHint(String hint) {
        this.hint = hint;
    }

    public void setText(String text) {
        this.text = text;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_edit);

        titleText = findViewById(R.id.dialog_title);
        editText = findViewById(R.id.dialog_edit);

        if (!DataUtil.isEmptyOr(title)) {
            titleText.setText(title);
        }

        if (!DataUtil.isEmptyOr(text)) {
            editText.setText(text);
            editText.setSelection(text.length());
        } else if (!DataUtil.isEmptyOr(hint)) {
            editText.setHint(hint);
            editText.clearFocus();
        }

        findViewById(R.id.dialog_cancel).setOnClickListener(v -> {
            cancel();
        });
        findViewById(R.id.dialog_submit).setOnClickListener(v -> {
            if (null != editDialogCallback) {
                Editable e = editText.getText();
                if (null == e) {
                    Toast.makeText(context, "输入有误,不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                String text = e.toString();
                if (DataUtil.isEmptyOr(text)) {
                    Toast.makeText(context, "输入有误,不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                editDialogCallback.editCallback(text);
            }
            cancel();
        });
    }

    public interface EditDialogCallback {
        void editCallback(String text);
    }

    public void setEditCallback(EditDialogCallback editDialogCallback) {
        this.editDialogCallback = editDialogCallback;
    }

}
